<template>
  <div>
    <a-upload
        :before-upload="beforeUpload"
        :custom-request="customRequest"
        :show-upload-list="false"
    >
      <a-button>选择文件</a-button>
    </a-upload>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';

// 定义分片大小，这里设置为 1MB
const CHUNK_SIZE = 1 * 1024 * 1024;

// 存储选择的文件
const selectedFile = ref<File | null>(null);

// 上传前的处理函数
const beforeUpload = (file: File) => {
  selectedFile.value = file;
  return false; // 阻止默认上传行为
};

// 自定义上传请求函数
const customRequest = async () => {
  if (!selectedFile.value) return;

  const file = selectedFile.value;
  const fileSize = file.size;
  const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);

  // 循环上传每个分片
  for (let i = 0; i < chunkCount; i++) {
    const start = i * CHUNK_SIZE;
    const end = Math.min(start + CHUNK_SIZE, fileSize);
    const chunk = file.slice(start, end);

    const formData = new FormData();
    formData.append('file', chunk);
    formData.append('filename', file.name);
    formData.append('chunkIndex', i.toString());
    formData.append('chunkCount', chunkCount.toString());

    try {
      // 发送分片上传请求
      await axios.post('http://localhost:8080/upload/chunk', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
    } catch (error) {
      message.error('分片上传失败');
      return;
    }
  }

  // 所有分片上传完成后，发送合并请求
  try {
    await axios.post('http://localhost:8080/upload/merge', {
      filename: file.name,
      chunkCount: chunkCount
    });
    message.success('文件上传成功');
  } catch (error) {
    message.error('文件合并失败');
  }
};
</script>
